import Vue from 'vue'
import Cookies from 'js-cookie'
import ClientOauth2 from 'client-oauth2'
import mouAxios from 'axios'

const accessToken = 'accessToken'
const orginalRoute  = 'orginalRoute'
const mouUser  = 'mouUser'

const oauth2 = {}

let defaultOauth2Config = {
  enable: true,
  whiteList: []
}

let localOauth2Config
let localRouter
let localAxios
let clientOauth2

oauth2.install = function(Vue, {router, axios = mouAxios, oauth2Config}) {
  localRouter = router
  localAxios = axios
  localOauth2Config = Object.assign(defaultOauth2Config, oauth2Config)
  console.log(localOauth2Config);

  clientOauth2 = new ClientOauth2({
    clientId: localOauth2Config.clientId,
    authorizationUri: localOauth2Config.authServer + '/oauth/authorize',
    redirectUri: window.location.href.replace(window.location.hash, ""),
    scope: ['all'],
  })

  router.beforeEach((to, from, next) => {
    if (shouldIntercept(to)) {
      getUserInfo()
        .then(() => {
          if (isLogin()) {
            localAxios.defaults.headers.common['Authorization'] = getBearerSchema()
            localAxios.defaults.headers.common['CurrentUser'] = getUser().username
            next()
          } else {
            getToken()
              .then(getUserInfo)
              .then(setAxoisDefaultAuthorization)
              .then(restoreRoutePath)
              .catch(() => {
                storeRoutePath(to)
                redirectToLoginPage()
              })
          }
        })
        .catch(() => {
            Cookies.remove(accessToken)
            Cookies.remove(mouUser)
            getToken()
              .then(getUserInfo)
              .then(setAxoisDefaultAuthorization)
              .then(restoreRoutePath)
            .catch(() => {
              storeRoutePath(to)
              redirectToLoginPage()
            })
        })
    } else {
      // 页面刷新后, axios 的这个设置就没有了,
      // 虽然有点每次进路由都会走这个, 还是在这里重新设置一下,
      if (isLogin()) {
        localAxios.defaults.headers.common['Authorization'] = getBearerSchema()
        localAxios.defaults.headers.common['CurrentUser'] = getUser().username
      }
      next()
    }
  })
}

function setAxoisDefaultAuthorization(user) {
  localAxios.defaults.headers.common['Authorization'] = getBearerSchema()
  localAxios.defaults.headers.common['CurrentUser'] = user.username
  return user
}

function shouldIntercept (route) {

  if (!localOauth2Config.enable) {
    return false
  }

  for (let pattern of localOauth2Config.whiteList) {
    if (RegExp(pattern, 'g').test(route.path)) {
      return false;
    }
  }

  return true

}

function getToken () {
  return clientOauth2.token.getToken(window.location.href.replace("#/","#"))
    .then(user => {
      if (!user.accessToken) {
        throw 'Not Authorized.'
      }
      Cookies.set(accessToken, user.accessToken)
      return user
    })
}

function getUserInfo (user) {
    // headers: {
    //   Authorization: getBearerSchema(),
    // },
    // withCredentials: true,
    // maxRedirects: 0,
  let config = {
    method: 'get',
    url: localOauth2Config.authServer + '/user/me',
    headers: {
      Authorization: getBearerSchema(),
    },
    withCredentials: true,
  }

  return localAxios.create().request(config).then(response => {
    if (response.data.toString().indexOf('doctype html') != -1) {
      console.log("redirect to login page")
      throw '/user/me 302 found'
    }
    Cookies.set(mouUser, response.data)
    return response.data
  })
}

function getBearerSchema () {
  return "Bearer " + Cookies.get(accessToken)
}

function restoreRoutePath () {
  if (Cookies.get(orginalRoute) == null) {
    console.log("There is not store route, redirect to /")
    localRouter.push('/')
  } else {
    let route = Cookies.get(orginalRoute)
    console.log("restore route: " + route)
    Cookies.remove(orginalRoute)
    localRouter.push(route)
  }
}

function storeRoutePath (route) {
  console.log("store route path " + route.fullPath)
  Cookies.set(orginalRoute, route.fullPath)
}

function redirectToLoginPage () {
  window.location = clientOauth2.token.getUri()
}


function getUser () {
  return JSON.parse(Cookies.get(mouUser))
}

function isNotLogin () {
  return !isLogin()
}

function isLogin () {
  return Cookies.get(accessToken)
}

function logout () {
  Cookies.remove(accessToken)
  Cookies.remove(mouUser)
    // 解决在加入自定义请求头CurrentUser后，无法注销系统的问题。
  delete localAxios.defaults.headers.common['CurrentUser']
  //logoutFromAuthServer().then(redirectToLoginPage)
  // 退出修改：解决portal二级页面退出再登录直接到一级界面的问题
  logoutFromAuthServer().then(window.location.reload())
}

function logoutFromAuthServer  () {
  let config = {
    method: 'get',
    url: localOauth2Config.authServer + '/logout',
    headers: {
      Authorization: getBearerSchema()
    },
    withCredentials: true
  }

  return localAxios.request(config)
}

export default oauth2
export { getUser, logout, isNotLogin,getBearerSchema }
